#!/usr/bin/env bash
############################################
proot_management_menu() {
	case ${TMOE_CHROOT} in
	false) TMOE_TIPS_02='' ;;
	*) TMOE_TIPS_02='\nchroot在未umount前remove将导致宿主系统重要数据被清空' ;;
	esac
	RETURN_TO_WHERE='proot_management_menu'
	CURRENT_DIR="$(pwd)"
	TMOE_CONTAINER_FORTUNE=true
	TMOE_CONTAINER_HITOKOTO=true
	MACHINE_NAME=$(printf "%s\n" ${DEBIAN_FOLDER} | sed 's@_@-@g')
	proot_management_menu_en() {
		SELECTED_GNU_LINUX=$(whiptail --title "${DEBIAN_FOLDER}" --menu "CONTAINER_DIR=${DEBIAN_CHROOT_MIN}\nFor non-special circumstances,please do not run rm -rf \${CONTAINER_DIR} manually." 0 50 0 \
			"1" "🌱 start ${DEBIAN_FOLDER}" \
			"2" "⏹️ kill process" \
			"3" "🐯 startvnc(tiger/tight)" \
			"4" "⚒️ startxsdl" \
			"5" "🍬 novnc(HTML5 VNC client)" \
			"6" "⚔️ startx11vnc" \
			"7" "🍹 backup ${CONTAINER_TYPE} container" \
			"8" "😏 unmount & remove" \
			"9" "📡 readme" \
			"10" "🥤 edit script" \
			"11" "🍅 space occupation" \
			"0" "🌚 Return to previous menu" \
			3>&1 1>&2 2>&3)
	}
	proot_management_menu_cn() {
		SELECTED_GNU_LINUX=$(whiptail --title "${DEBIAN_FOLDER_CAPITAL}" --menu "容器路径为${DEBIAN_CHROOT_MIN}\n非特殊情况下,请在本工具内正常移除容器,请勿手动rm -rf \${容器路径}${TMOE_TIPS_02}" 0 50 0 \
			"1" "🌱 启动${CONTAINER_TYPE} ${DEBIAN_FOLDER}" \
			"2" "⏹️ 停止容器进程" \
			"3" "🐯 startvnc:启动tiger/tightvnc" \
			"4" "⚒️ startxsdl:启动xsdl/VcXsrv" \
			"5" "🍬 novnc:在浏览器里连接vnc" \
			"6" "⚔️ startx11vnc:启动x11vnc" \
			"7" "🍹 backup 备份${CONTAINER_TYPE}容器" \
			"8" "😏 unmount & remove 卸载并移除" \
			"9" "📡 readme 自述/说明" \
			"10" "🥤 edit script 编辑脚本" \
			"11" "🍅 space occupation 空间占用大小" \
			"0" "🌚 back 返回上级菜单" \
			3>&1 1>&2 2>&3)
	}
	proot_management_menu_de() {
		SELECTED_GNU_LINUX=$(whiptail --title "${DEBIAN_FOLDER}" --menu "CONTAINER_DIR=${DEBIAN_CHROOT_MIN}\nFühren Sie rm -rf \${CONTAINER_DIR} unter nicht besonderen Umständen nicht manuell aus." 0 50 0 \
			"1" "🌱 start ${DEBIAN_FOLDER}" \
			"2" "⏹️ Tötungsprozess" \
			"3" "🐯 startvnc(tiger/tight)" \
			"4" "⚒️ startxsdl" \
			"5" "🍬 novnc(HTML5 VNC client)" \
			"6" "⚔️ startx11vnc" \
			"7" "🍹 backup ${CONTAINER_TYPE} container" \
			"8" "😏 aushängen und entfernen" \
			"9" "📡 Liesmich" \
			"10" "🥤 Skript bearbeiten" \
			"11" "🍅 Raumbesetzung" \
			"0" "🌚 zurück" \
			3>&1 1>&2 2>&3)
	}
	case ${TMOE_MENU_LANG} in
	zh_*UTF-8) proot_management_menu_cn ;;
	de_DE.UTF-8) proot_management_menu_de ;; #Deutsche
	*) proot_management_menu_en ;;
	esac
	##############################
	case "${SELECTED_GNU_LINUX}" in
	0 | "") ${RETURN_TO_MENU} ;;
	1) normally_start_gnu_linux_distro ;;
	2) kill_container_process ;;
	3) start_gnu_linux_distro_tigervnc ;;
	4) start_gnu_linux_distro_x ;;
	5) install_web_novnc ;;
	6) start_gnu_linux_distro_x11vnc ;;
	7) backup_tmoe_gnu_linux_distro ;;
	8) umount_and_remove_gnu_linux_distro ;;
	9) readme_of_gnu_linux_distro ;;
	10) edit_container_startup_script ;;
	11) du_sh_gnu_linux_distro ;;
	esac
	#"9" "🥤 install 安装" \ 9) install_new_tmoe_gnu_linux_distro ;;
	####################
	case "${SELECTED_GNU_LINUX}" in
	2 | 7 | 9 | 10 | 11)
		#回到本菜单： 停止进程,备份，命令，空间 ,编辑
		press_enter_to_return
		proot_management_menu
		;;
	8)
		#unmount & remove
		${RETURN_TO_MENU}
		;;
	esac
	#卸载之后要回到发行版选择菜单，而非当前发行版菜单
}
##############################
edit_container_startup_script() {
	for i in editor vim nano vi; do
		if [ $(command -v ${i}) ]; then
			${TMOE_PREFIX} ${i} ${DEBIAN_CHROOT}/usr/local/etc/tmoe-linux/container/tmoe-linux-container
			break
		fi
	done
}
#####################
#EXEC_LSOF=$(sed -n p ${LSOF_TEMP_FILE})
check_tmoe_container_pid() {
	LIST_OPEN_FILES_COUNTS=$(awk '{print $1}' ${LSOF_TEMP_FILE} | grep -c '^lsof')
	case ${LIST_OPEN_FILES_COUNTS} in
	0)
		LIST_OPEN_FILES=$(grep "${DEBIAN_CHROOT%/}" ${LSOF_TEMP_FILE} | awk '{print $1}' | uniq)
		KILL_PID=$(printf "%s\n" "${LIST_OPEN_FILES}" | sed "s@^@pkill -9 @g")
		;;
	*)
		LIST_OPEN_FILES=$(grep "${DEBIAN_CHROOT%/}" ${LSOF_TEMP_FILE} | awk '{print $2}' | uniq)
		KILL_PID=$(printf "%s\n" "${LIST_OPEN_FILES}" | sed "s@^@kill -9 @g")
		;;
	esac
	PROCESS_ID_AND_NAME=$(grep "${DEBIAN_CHROOT%/}" ${LSOF_TEMP_FILE} | awk '{print $2,$1}' | uniq)

	printf "${PURPLE}"
	cat <<-EOF
		${PROCESS_ID_AND_NAME}
	EOF
	printf "${RESET}"
	printf '%s\n' '--------------------'
	case ${LIST_OPEN_FILES} in
	"") ;;
	*) printf "%s\n" "${KILL_PID}" ;;
	esac
}
##################
tips_of_check_pid() {
	printf "${GREEN}%s ${YELLOW}%s${RESET}\n" "DETECTING" "PROCESS ID ..."
	printf "${BLOD}${YELLOW}%s${RESET}\n" "正在检测${DEBIAN_FOLDER}运行中的进程："
	LSOF_TEMP_FILE="${TMPDIR}/.lsof.tmp"
	[[ ! -e ${LSOF_TEMP_FILE} ]] || rm -f ${LSOF_TEMP_FILE}
	[[ ! -e ${LSOF_TEMP_FILE}.02 ]] || rm -f ${LSOF_TEMP_FILE}.02
}
##########
tips_of_kill_pid() {
	printf "${RED}%s ${BLUE}%s${RESET}\n" "${PROCESS_ID_AND_NAME}" | sed "s@^@Killed @g"
	printf "${BOLD}${YELLOW}%s\n" "All processes have been killed."
	printf "%s\n" "已${RED}终止${BLUE}${DEBIAN_FOLDER}${RESET}容器进程"
	[[ ! -e ${LSOF_TEMP_FILE} ]] || rm -f ${LSOF_TEMP_FILE}
}
##########
kill_chroot_container_process() {
	case ${SYSTEMD_NSPAWN} in
	true) machinectl terminate ${MACHINE_NAME} ;;
	esac
	#if [ -e "${DEBIAN_CHROOT}/run/dbus/pid" ]; then
	#	DBUS_PID="$(sed -n p ${DEBIAN_CHROOT}/run/dbus/pid)"
	#	su -c "kill -9 ${DBUS_PID} 2>/dev/null"
	#fi

	#for i in /run/dbus/pid /tmp/.X1-lock /tmp/.X11-unix/X1; do
	#	if [ -e "${DEBIAN_CHROOT}${i}" ]; then
	#		sudo rm -vf ${DEBIAN_CHROOT}${i}
	#	fi
	#done
	tips_of_check_pid
	#EXEC_LSOF=$(su -c "lsof")

	su -c "lsof ${DEBIAN_CHROOT%/}" >${LSOF_TEMP_FILE}.02
	if [[ $(command -v batcat) ]]; then
		batcat -ppn -l ruby ${LSOF_TEMP_FILE}.02
	elif [[ $(command -v bat) ]]; then
		bat -ppn -l ruby ${LSOF_TEMP_FILE}.02
	else
		cat ${LSOF_TEMP_FILE}.02
	fi

	LIST_OPEN_FILES_02=$(awk '{print $2}' ${LSOF_TEMP_FILE}.02 | sed 1d | uniq)
	KILL_PID_02=$(printf "%s\n" "${LIST_OPEN_FILES_02}" | sed "s@^@${GREEN}sudo ${RED}kill -9${BLUE} @g")
	if [[ -n ${LIST_OPEN_FILES_02} ]]; then
		case ${TMOE_MENU_LANG} in
		zh_*UTF-8) printf "%s\n" "若无法${RED}终止${RESET}${BLUE}容器进程${RESET}，则请${PURPLE}手动执行${RESET}以下${GREEN}sudo${RESET}开头的命令。" ;;
		esac
		printf "%s\n" "If you can not ${RED}kill${RESET} these ${BLUE}processes${RESET},try running ${GREEN}the following commands.${RESET}"
		printf "%s\n" "${GREEN}${KILL_PID_02}${RESET}"
	fi
	#此处执行bash -c "${KILL_PID_02}"会导致tmoe-manager退出。

	su -c "lsof" >${LSOF_TEMP_FILE}
	check_tmoe_container_pid
	su -c "${KILL_PID}"
	#必须在kill掉进程后再umount
	source ${TMOE_SHARE_DIR}/removal/umount
	tips_of_kill_pid
}
kill_proot_container_process() {
	tips_of_check_pid
	#EXEC_LSOF=$(lsof 2>/dev/null)
	lsof 2>/dev/null >${LSOF_TEMP_FILE}
	check_tmoe_container_pid
	bash -c "${KILL_PID}"
	tips_of_kill_pid
}
################
kill_container_process() {
	#printf "%s\n" "Sorry,由于本功能在调试中出现bug，因次无法准确地检测容器进程。"
	#printf "%s\n" "Please look forward to the stable version tomorrow."
	case ${TMOE_CHROOT} in
	true) kill_chroot_container_process ;;
	*) kill_proot_container_process ;;
	esac
}
##############
readme_of_gnu_linux_distro() {
	LONG_DISTRO_NAME=$(printf '%s\n' "${TMOE_LINUX_CONTAINER_DISTRO}" | awk -F '-' '{print $1}')
	LONG_DISTRO_CODE=$(printf '%s\n' "${TMOE_LINUX_CONTAINER_DISTRO}" | awk -F '-' '{print $2}')
	[[ ! $(printf '%s\n' "${TMOE_LINUX_CONTAINER_DISTRO}" | awk -F '-' '{print $3}') = Stream ]] || LONG_DISTRO_CODE=$(printf '%s\n' "${TMOE_LINUX_CONTAINER_DISTRO}" | awk -F '-' '{print $2"-"$3}')
	case ${LONG_DISTRO_NAME} in
	arch) SHORT_DISTRO_NAME='a' ;;
	alpine) SHORT_DISTRO_NAME='ap' ;;
	armbian) SHORT_DISTRO_NAME='arm' ;;
	centos) SHORT_DISTRO_NAME='c' ;;
	debian) SHORT_DISTRO_NAME='d' ;;
	fedora) SHORT_DISTRO_NAME='f' ;;
	funtoo) SHORT_DISTRO_NAME='ft' ;;
	gentoo) SHORT_DISTRO_NAME='g' ;;
	kali) SHORT_DISTRO_NAME='k' ;;
	mint) SHORT_DISTRO_NAME='mi' ;;
	manjaro) SHORT_DISTRO_NAME='m' ;;
	opensuse) SHORT_DISTRO_NAME='o' ;;
	openwrt) SHORT_DISTRO_NAME='ow' ;;
	raspbios) SHORT_DISTRO_NAME='r' ;;
	slackware) SHORT_DISTRO_NAME='s' ;;
	ubuntu) SHORT_DISTRO_NAME='u' ;;
	void) SHORT_DISTRO_NAME='v' ;;
	*) SHORT_DISTRO_NAME=${LONG_DISTRO_NAME} ;;
	esac
	case ${TMOE_CHROOT} in
	true) SHORT_VIRT_TYPE='c' ;;
	*) SHORT_VIRT_TYPE='p' ;;
	esac
	case "${LONG_DISTRO_CODE}" in
	focal) SHORT_DISTRO_CODE='20.04' ;;
	groovy) SHORT_DISTRO_CODE='20.10' ;;
	sid) SHORT_DISTRO_CODE='s' ;;
	bionic) SHORT_DISTRO_CODE='18.04' ;;
	rolling) SHORT_DISTRO_CODE='r' ;;
	8-Stream) SHORT_DISTRO_CODE='8s' ;;
	9-Stream) SHORT_DISTRO_CODE='9s' ;;
	"") SHORT_DISTRO_CODE="" ;;
	*) SHORT_DISTRO_CODE=${LONG_DISTRO_CODE} ;;
	esac
	case ${ARCH_TYPE} in
	amd64) SHORT_ARCH='x' ;;
	arm64) SHORT_ARCH='a' ;;
	armhf) SHORT_ARCH='h' ;;
	armel) SHORT_ARCH='armel' ;;
	i386) SHORT_ARCH='i' ;;
	ppc*) SHORT_ARCH='p' ;;
	s390*) SHORT_ARCH='s390' ;;
	mips64el) SHORT_ARCH='m64' ;;
	mipsel) SHORT_ARCH='m' ;;
	risc*) SHORT_ARCH='risc' ;;
	esac
	cat <<-EOF
		${BOLD}${YELLOW}Full command:${RESET} ${PURPLE}tmoe ${CONTAINER_TYPE} ${LONG_DISTRO_NAME} ${LONG_DISTRO_CODE} ${ARCH_TYPE}${RESET}
		${BOLD}${YELLOW}Simplified command:${RESET}  ${BLUE}tmoe ${SHORT_VIRT_TYPE} ${SHORT_DISTRO_NAME} ${SHORT_DISTRO_CODE} ${SHORT_ARCH}${RESET}
		${BOLD}${YELLOW}Start ${DEBIAN_FOLDER} + tigervnc server:${RESET} ${GREEN}tmoe ${SHORT_VIRT_TYPE} ${SHORT_DISTRO_NAME} ${SHORT_DISTRO_CODE} ${SHORT_ARCH} v${RESET}
		${BOLD}${YELLOW}Start ${DEBIAN_FOLDER} + x11vnc server:${RESET} ${GREEN}tmoe ${SHORT_VIRT_TYPE} ${SHORT_DISTRO_NAME} ${SHORT_DISTRO_CODE} ${SHORT_ARCH} x11${RESET}
		${BOLD}${YELLOW}Start ${DEBIAN_FOLDER} + X server:${RESET} ${GREEN}tmoe ${SHORT_VIRT_TYPE} ${SHORT_DISTRO_NAME} ${SHORT_DISTRO_CODE} ${SHORT_ARCH} xs${RESET}
		The default ${YELLOW}login shell${RESET} is ${GREEN}zsh${RESET}, if you want to start ${BLUE}bash${RESET},then type ${GREEN}tmoe ${SHORT_VIRT_TYPE} ${SHORT_DISTRO_NAME} ${SHORT_DISTRO_CODE} ${SHORT_ARCH} bash${RESET}
		Start ${BLUE}ash${RESET} as a login shell：  ${GREEN}tmoe ${SHORT_VIRT_TYPE} ${SHORT_DISTRO_NAME} ${SHORT_DISTRO_CODE} ${SHORT_ARCH} ash${RESET} 
		--------------------
		启动${DEBIAN_FOLDER}的完整命令为 ${PURPLE}tmoe ${CONTAINER_TYPE} ${LONG_DISTRO_NAME} ${LONG_DISTRO_CODE} ${ARCH_TYPE}${RESET}
		若您未选择跨架构运行，则可去除${PURPLE}${ARCH_TYPE}${RESET}参数。
		精简命令为  ${BLUE}tmoe ${SHORT_VIRT_TYPE} ${SHORT_DISTRO_NAME} ${SHORT_DISTRO_CODE} ${SHORT_ARCH}${RESET}
		若您使用的是tmoe-zsh配置的环境，则可以进一步简化为 ${YELLOW}t ${SHORT_VIRT_TYPE} ${SHORT_DISTRO_NAME} ${SHORT_DISTRO_CODE} ${SHORT_ARCH}${RESET}
		同时启动${BLUE}${DEBIAN_FOLDER}${RESET}容器+${YELLOW}tigervnc server${RESET}的命令为  ${GREEN}tmoe ${SHORT_VIRT_TYPE} ${SHORT_DISTRO_NAME} ${SHORT_DISTRO_CODE} ${SHORT_ARCH} v${RESET}
		同时启动${BLUE}${DEBIAN_FOLDER}${RESET}容器+${YELLOW}x11vnc server${RESET}的命令为  ${GREEN}tmoe ${SHORT_VIRT_TYPE} ${SHORT_DISTRO_NAME} ${SHORT_DISTRO_CODE} ${SHORT_ARCH} x11${RESET}
		同时启动${BLUE}${DEBIAN_FOLDER}${RESET}容器+${YELLOW}XSDL/VcXsrv${RESET}的命令为  ${GREEN}tmoe ${SHORT_VIRT_TYPE} ${SHORT_DISTRO_NAME} ${SHORT_DISTRO_CODE} ${SHORT_ARCH} xs${RESET}
		容器的默认${YELLOW}登录SHELL${RESET}为${GREEN}zsh${RESET},若您需要使用其它${YELLOW}shell${RESET}，则请使用以下命令
		临时使用${GREEN}bash${RESET}作为${YELLOW}登录SHELL${RESET}：  ${GREEN}tmoe ${SHORT_VIRT_TYPE} ${SHORT_DISTRO_NAME} ${SHORT_DISTRO_CODE} ${SHORT_ARCH} bash${RESET}  
		临时使用${GREEN}ash${RESET}作为${YELLOW}登录SHELL${RESET}：  ${GREEN}tmoe ${SHORT_VIRT_TYPE} ${SHORT_DISTRO_NAME} ${SHORT_DISTRO_CODE} ${SHORT_ARCH} ash${RESET} 
		--------------------
		${BOLD}额外拓展功能${RESET}
		${YELLOW}（补全功能）${RESET}说明${RESET}
		${YELLOW}shell环境要求${RESET}：${GREEN}zsh${RESET}
		The completion function exists separately as a zsh plugin, so bash and other shells are not supported.
		仅支持${GREEN}zsh${RESET},${RED}不支持${RESET}${PURPLE}bash${RESET}

		tmoe-zsh会自动加载tmoe补全插件，其他插件管理器需要手动加载。
		zinit插件管理器配置补全插件：${GREEN}
		[[ \$(egrep '^[^#]*zinit.*completion/_tmoe' ${HOME}/.zshrc) ]] || sed -i '$ a\zinit ice lucid wait=1 as"completion" && zinit snippet ${TMOE_SHARE_DIR}/completion/_tmoe' ${HOME}/.zshrc
		${RESET}
		至于其他插件管理器，例如oh-my-zsh，因开发者并未进行测试，故请自行加载插件。
		${BOLD}${YELLOW}TIPS OF TMOE COMPLETION PLUGIN${RESET}${RESET}
		  1.在TMOE-ZSH配置的环境下,输${YELLOW}t${RESET},按下空格,再按下TAB键${BLUE}⇄${RESET}进行补全，输${GREEN}/${RESET}进行连续补全，在该模式下支持搜索发行版名称。
		  2.在其他插件管理器配置的环境下，输入${YELLOW}tmoe${RESET},不按回车,按下TAB键${BLUE}⇄${RESET}进行补全.
		  Type ${GREEN}tmoe${RESET}, then don't press ${RED}enter${RESET}, press Tab${BLUE}⇄${RESET} key to complete.
	EOF
	case ${SYSTEMD_NSPAWN} in
	true)
		cat <<-EOF
			检测到您选择的systemd-nspawn容器，在进入容器后，按下${GREEN}Ctrl${RESET}+三次${YELLOW}]]]${RED}退出${RESET}。
			您可以使用${GREEN}machinectl${RESET}来管理nspawn容器。
			${GREEN}machinectl -h${RESET} 获取帮助信息 get help info
			${GREEN}machinectl list${RESET} 列出容器
			${GREEN}machinectl terminate ${DEBIAN_FOLDER}-${ARCH_TYPE}${RESET} 终止容器
		EOF
		;;
	esac
}
######
if_container_is_not_installed() {
	[[ -e ${DEBIAN_CHROOT} ]] || install_new_tmoe_gnu_linux_distro
	case ${DEB_BOOT_STRAP} in
	true) install_new_tmoe_gnu_linux_distro ;;
	esac
}
git_pull_tmoe_linux() {
	cd ${TMOE_GIT_DIR}
	git reset --hard origin/master
	git pull --rebase --stat origin master --allow-unrelated-histories || git rebase --skip
	cd ${CURRENT_DIR}

}
normally_start_gnu_linux_distro() {
	source ${CONFIG_FOLDER}/hitokoto.conf
	case ${TMOE_CONTAINER_FORTUNE} in
	true)
		if [ $(command -v fortune) ]; then
			fortune 2>/dev/null
		elif [ -e /usr/games/fortune ]; then
			/usr/games/fortune 2>/dev/null
		fi
		;;
	esac
	case ${TMOE_CONTAINER_HITOKOTO} in
	true) [[ ! ${TMOE_LANG} =~ zh_.*UTF-8 ]] || get_hitokito_cn ;;
	esac
	if_container_is_not_installed
	cat_release_file
	case $(uname -o) in
	Android)
		[[ ! $(command -v termux-wake-unlock) ]] || termux-wake-lock 2>/dev/null
		;;
	esac

	if [[ $(command -v pulseaudio) && $(id -u) != 0 ]]; then
		pulseaudio --start
	fi
	case ${SYSTEMD_NSPAWN} in
	true)
		source ${TMOE_SHARE_DIR}/removal/umount
		source ${TMOE_SHARE_DIR}/container/nspawn/startup
		;;
	*) ${TMOE_PREFIX} bash ${DEBIAN_CHROOT}/usr/local/etc/tmoe-linux/container/tmoe-linux-container ;;
	esac
	if [[ -e ${DEBIAN_CHROOT} ]]; then
		press_enter_to_return
		proot_management_menu
	fi
}
start_gnu_linux_distro_tigervnc() {
	[[ ! $(command -v am) ]] || am start -n com.realvnc.viewer.android/com.realvnc.viewer.android.app.ConnectionChooserActivity 2>/dev/null
	${TMOE_PREFIX} touch ${DEBIAN_CHROOT}/root/.vnc/startvnc
	normally_start_gnu_linux_distro
}
start_gnu_linux_distro_x11vnc() {
	[[ ! $(command -v am) ]] || am start -n com.realvnc.viewer.android/com.realvnc.viewer.android.app.ConnectionChooserActivity 2>/dev/null
	${TMOE_PREFIX} touch ${DEBIAN_CHROOT}/root/.vnc/startx11vnc
	normally_start_gnu_linux_distro
}
start_gnu_linux_distro_x() {
	[[ ! $(command -v am) ]] || am start -n x.org.server/x.org.server.MainActivity 2>/dev/null
	sleep 3
	${TMOE_PREFIX} touch ${DEBIAN_CHROOT}/root/.vnc/startxsdl
	normally_start_gnu_linux_distro
}
install_web_novnc() {
	#source ${TMOE_SHARE_DIR}/app/novnc
	NOVNC_PORT=$(grep '^NOVNC_PORT=' ${DEBIAN_CHROOT}/usr/local/bin/novnc | head -n 1 | awk -F '=' '{print $2}' | cut -d '"' -f 2)
	[[ -n ${NOVNC_PORT} ]] || NOVNC_PORT=36080
	NOVNC_ADDR="http://localhost:${NOVNC_PORT}/vnc.html"
	printf "${YELLOW}%s${RESET}\n" "${NOVNC_ADDR}"
	if [[ $(command -v am) ]]; then
		am start -a android.intent.action.VIEW -d "${NOVNC_ADDR}" 2>/dev/null
	elif [[ $(command -v xdg-open) ]]; then
		xdg-open ${NOVNC_ADDR} 2>/dev/null
	elif [[ -e /mnt/c/WINDOWS/system32/cmd.exe ]]; then
		/mnt/c/WINDOWS/system32/cmd.exe /c "start ${NOVNC_ADDR}"
	fi
	${TMOE_PREFIX} touch ${DEBIAN_CHROOT}/root/.vnc/novnc
	normally_start_gnu_linux_distro
}
install_new_tmoe_gnu_linux_distro() {
	check_tmoe_completion_version
	check_tmoe_completion
	git_pull_tmoe_linux
	###
	case ${WEEKLY_BUILD_CONTAINER} in
	true) install_weekly_build_container ;;
	*)
		case ${ARCH_TYPE} in
		mips* | risc*) ;;
		*)
			case ${DISTRO_NAME} in
			debian) check_debian_distro_code ;;
			ubuntu) check_ubuntu_distro_code ;;
			kali) install_kali_rolling_gnu_linux_distro ;;
			arch) install_arch_linux_distro ;;
			esac
			;;
		esac
		;;
	esac
}
##########
bat_build_latest_txt() {
	if [[ -e ${BUILD_LATEST_TXT} ]]; then
		if [[ $(command -v bat) ]]; then
			bat -ppn -l sh ${BUILD_LATEST_TXT}
		elif [[ $(command -v batcat) ]]; then
			batcat -ppn -l sh ${BUILD_LATEST_TXT}
		else
			cat ${BUILD_LATEST_TXT}
		fi
		printf "${BLUE}-----------------------------------------${RESET}\n"
	fi
}
bat_build_latest02_txt() {
	BUILD_LATEST_TXT=${CONFIG_FOLDER}/build-latest02.txt
	bat_build_latest_txt
}
bat_build_latest01_txt() {
	BUILD_LATEST_TXT=${CONFIG_FOLDER}/build-latest01.txt
	bat_build_latest_txt
}

install_weekly_build_container() {
	NODE_NAME='node01-azure'
	case ${NODE02_ENABLED} in
	true)
		if (whiptail --title "NETWORK NODE" --yes-button 'node01-azure' --no-button 'node02-tmoe' --yesno "Please choose a network node\n请选择网络节点" 8 50); then
			NODE_URL="${NODE01_URL}"
		else
			NODE_NAME='node02-tmoe'
			NODE_URL="${NODE02_URL}"
		fi
		;;
	*) NODE_URL="${NODE01_URL}" ;;
	esac
	printf "%s\n" "本容器使用以下Dockerfile进行构建。"
	DOCKERFILE="${TMOE_SHARE_DIR}/docker-build/${ARCH_TYPE}/${TMOE_LINUX_CONTAINER_DISTRO}/${DESKTOP}/Dockerfile"
	printf "%s\n" "${BLUE}${DOCKERFILE}${RESET}"
	if [ $(command -v bat) ]; then
		bat -ppn "${DOCKERFILE}"
	else
		cat "${DOCKERFILE}"
	fi
	for i in ${CONFIG_FOLDER}/build-latest02.txt ${CONFIG_FOLDER}/build-latest01.txt; do
		if [[ -e ${i} ]]; then
			rm -f ${i}
		fi
	done
	BUILD_TXT="${ARCH_TYPE}/${TMOE_LINUX_CONTAINER_DISTRO}/${DESKTOP}/build.txt"
	printf "%s\n" "正在获取版本信息..."
	printf "%s\n" "Getting ${DEBIAN_FOLDER} version info..."
	ROOTFS_VERSION='latest02'

	case ${NODE_NAME} in
	node02-tmoe)
		aria2c --console-log-level=error --no-conf --allow-overwrite=true --http-user=${NODE02_USER} --http-passwd=${NODE02_PW} -d ${CONFIG_FOLDER} -o build-latest02.txt ${NODE_URL}/latest02/${BUILD_TXT}
		bat_build_latest02_txt
		;;
	*)
		aria2c --console-log-level=error --no-conf --allow-overwrite=true -d ${CONFIG_FOLDER} -o build-latest02.txt ${NODE_URL}/latest02/${BUILD_TXT}
		bat_build_latest02_txt
		aria2c --console-log-level=error --no-conf --allow-overwrite=true -d ${CONFIG_FOLDER} -o build-latest01.txt ${NODE_URL}/latest01/${BUILD_TXT}
		if grep -q 'DOCTYPE html' ${CONFIG_FOLDER}/build-latest01.txt; then
			rm -f ${CONFIG_FOLDER}/build-latest01.txt
		elif ! grep -q 'STATUS=completed' ${CONFIG_FOLDER}/build-latest01.txt; then
			ROOTFS_VERSION='latest02'
		elif ! grep -q 'STATUS=completed' ${CONFIG_FOLDER}/build-latest02.txt; then
			ROOTFS_VERSION='latest01'
		else
			LATEST_01_DATE="$(grep 'BUILD_DATE=' ${CONFIG_FOLDER}/build-latest01.txt | awk -F'=' '{print $2}')"
			LATEST_02_DATE="$(grep 'BUILD_DATE=' ${CONFIG_FOLDER}/build-latest02.txt | awk -F'=' '{print $2}')"
			LATEST_01_TIME="$(date -d $(grep 'END_TIME=' ${CONFIG_FOLDER}/build-latest01.txt | awk -F'=' '{print $2}') +%s)"
			LATEST_02_TIME="$(date -d $(grep 'END_TIME=' ${CONFIG_FOLDER}/build-latest02.txt | awk -F'=' '{print $2}') +%s)"
			if ((${LATEST_02_DATE} < ${LATEST_01_DATE})); then
				ROOTFS_VERSION='latest01'
			elif ((${LATEST_02_DATE} > ${LATEST_01_DATE})); then
				ROOTFS_VERSION='latest02'
			elif ((${LATEST_02_TIME} < ${LATEST_01_TIME})); then
				ROOTFS_VERSION='latest01'
			else
				ROOTFS_VERSION='latest02'
			fi
		fi
		bat_build_latest01_txt
		;;
	esac
	ROOTFS_FILE="$(grep 'ROOTFS_FILE=' ${CONFIG_FOLDER}/build-${ROOTFS_VERSION}.txt | awk -F'=' '{print $2}')"
	printf "%s\n" "Do you want to download ${BLUE}${ROOTFS_FILE}${RESET}(${YELLOW}${ROOTFS_VERSION}${RESET})?"
	case ${ROOTFS_VERSION} in
	latest01) ROOTFS_VERSION_02='latest02' ;;
	latest02) ROOTFS_VERSION_02='latest01' ;;
	esac
	do_you_want_to_continue
	if [[ -s ${CONFIG_FOLDER}/build-latest01.txt ]]; then
		if grep -q 'STATUS=completed' ${CONFIG_FOLDER}/build-latest01.txt; then
			if (whiptail --title "VERSION" --yes-button "${ROOTFS_VERSION}" --no-button "${ROOTFS_VERSION_02}" --yesno "Please choose a version.\n最新版为${ROOTFS_VERSION}" 8 50); then
				printf "%s\n" "${YELLOW}${ROOTFS_VERSION}${RESET}"
			else
				ROOTFS_VERSION=${ROOTFS_VERSION_02}
				printf "%s\n" "${PURPLE}${ROOTFS_VERSION}${RESET}"
			fi
		fi
	fi
	bash -c "$(sed -n p ${TMOE_SHARE_DIR}/container/install |
		sed "1a\WEEKLY_BUILD_CONTAINER=true" |
		sed "1a\DESKTOP=${DESKTOP}" |
		sed "1a\NODE_URL=${NODE_URL}" |
		sed "1a\NODE02_USER=${NODE02_USER}" |
		sed "1a\NODE02_PW=${NODE02_PW}" |
		sed "1a\ROOTFS_VERSION=${ROOTFS_VERSION}" |
		sed "1a\NODE_NAME=${NODE_NAME}" |
		sed "s@TMOE_ROOTFS_TAR_XZ=.*debian-sid_.*@TMOE_ROOTFS_TAR_XZ=${ROOTFS_FILE}@" |
		sed "s/debian system/${DISTRO_NAME} system/g" |
		sed "s@BFSU Open Source Mirror Station@${NODE_NAME}@" |
		sed "s:Debian GNU/Linux:${DISTRO_NAME} GNU/Linux:g")"
	#--http-user=${NODE02_USER} --http-passwd=${NODE02_PW}
}
#############
umount_and_remove_gnu_linux_distro() {
	kill_container_process
	source ${TMOE_SHARE_DIR}/container/remove
}
du_sh_gnu_linux_distro() {
	case ${TMOE_CHROOT} in
	true)
		printf "%s\n" "Unmounting dirs ..."
		su -c "umount -lvf ${DEBIAN_CHROOT}/* 2>/dev/null"
		su -c "umount -lvf ${DEBIAN_CHROOT}/*/*  2>/dev/null"
		su -c "umount -lvf ${DEBIAN_CHROOT}  2>/dev/null"
		;;
	esac
	printf "%s\n" "Detecting the space occupied by ${BLUE}${DEBIAN_FOLDER}${RESET} ..."
	printf "%s\n" "正在检测${BLUE}${DEBIAN_FOLDER}${RESET}占用空间大小..."
	case ${TMOE_CHROOT} in
	true)
		if [ -e "${DEBIAN_CHROOT}" ]; then
			cd ${DEBIAN_CHROOT}
			${TMOE_PREFIX} du -sh * 2>/dev/null
			printf "%s\n" "${YELLOW}正在列出排行榜...${RESET}"
			${TMOE_PREFIX} find ./ -type d \( -path="./proc" \
				-o -path="./root/sd" \
				-o -path="./root/tf" \
				-o -path="./root/termux" \
				-o -path="./media/sd" \
				-o -path="./media/termux" \
				-o -path="./media/tf" \
				-o -path="./sd" \
				-o -path="./tf" \
				-o -path="./dev" \
				-o -path="./sys" \
				-o -path="./system" \) -prune \
				-type f -print0 2>/dev/null |
				xargs -0 ${TMOE_PREFIX} du |
				sort -n |
				tail -10 |
				cut -f 2 |
				xargs -I{} ${TMOE_PREFIX} du -sh {}
		else
			printf "${RED}%s${RESET} ${BLUE}%s${RESET}\n" "You did not install" "${DEBIAN_FOLDER}"
		fi
		;;
	*)
		if [ -e "${DEBIAN_CHROOT}" ]; then
			cd ${DEBIAN_CHROOT}
			${TMOE_PREFIX} du -sh *
			printf "%s\n" "${YELLOW}正在列出TOP30...${RESET}"
			${TMOE_PREFIX} find ./ -type d \( -path="./proc" \
				-o -path="./root/sd" \
				-o -path="./root/tf" \
				-o -path="./root/termux" \
				-o -path="./media/sd" \
				-o -path="./media/termux" \
				-o -path="./media/tf" \
				-o -path="./sd" \
				-o -path="./tf" \
				-o -path="./dev" \
				-o -path="./sys" \
				-o -path="./system" \) -prune \
				-type f -print0 2>/dev/null |
				xargs -0 ${TMOE_PREFIX} du |
				sort -n |
				tail -30 |
				cut -f 2 |
				xargs -I{} ${TMOE_PREFIX} du -sh {}
		else
			printf "${RED}%s${RESET} ${BLUE}%s${RESET}\n" "You did not install" "${DEBIAN_FOLDER}"
		fi
		;;
	esac
}
######################
backup_tmoe_gnu_linux_distro() {
	if [[ ! -e ${DEBIAN_CHROOT} ]]; then
		cat <<-EOF
			您${RED}尚未安装${RESET}${BLUE}${DEBIAN_FOLDER_CAPITAL}${RESET}容器
			是否使用恢复容器的选项？
		EOF
		do_you_want_to_continue
		source ${TMOE_SHARE_DIR}/compression/restore
		restore_gnu_linux_container
	else
		case ${TMOE_CHROOT} in
		true) source ${TMOE_SHARE_DIR}/removal/umount ;;
		esac
		source ${TMOE_SHARE_DIR}/compression/backup
	fi
}
#####################
proot_management_menu $@
